package org.sukui.starter

import io.vertx.config.ConfigRetriever
import io.vertx.config.ConfigRetrieverOptions
import io.vertx.config.ConfigStoreOptions
import io.vertx.core.DeploymentOptions
import io.vertx.core.Future
import io.vertx.core.json.JsonObject
import io.vertx.kotlin.coroutines.CoroutineVerticle
import org.sukui.starter.verticles.DaoVerticle
import org.sukui.starter.verticles.WebVerticle


class MainVerticle : CoroutineVerticle() {

  override suspend fun start() {
    initConfig().onComplete { asyncResult ->
      if (asyncResult.succeeded()) {
        // web
        vertx.deployVerticle(WebVerticle().javaClass.name,
          DeploymentOptions()
            // 将配置信息传递
            .setConfig(asyncResult.result())
        )
        // Dao
        vertx.deployVerticle(DaoVerticle().javaClass.name,
          DeploymentOptions()
            .setWorker(true)
            .setConfig(asyncResult.result())
        )
      }
    }

  }

  // 初始化配置文件
  private fun initConfig(): Future<JsonObject> {

    val defaultConfig = ConfigStoreOptions()
      .setType("file")
      .setFormat("json")
      .setConfig(JsonObject().put("path", "config.json"))

    val opts = ConfigRetrieverOptions()
      .addStore(defaultConfig)

    val cfgRetriever = ConfigRetriever.create(vertx, opts)

    return cfgRetriever.config
  }

}
